{% extends 'base.html' %}
{% block title %}
    {{classname}} - 班级管理仪表盘
{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>{{classname}} 班级管理仪表盘</h2>
        <div>
            <span class="me-3">{{ strdate|date:"Y年n月j日" }} {{ weekday }}</span>
            {% for birthday in get_birthday_by_classid %}
            <span id="birthday" class="text-danger badge bg-danger">今天是{{birthday.name}}的生日！<i class="bi bi-cake"></i></span>
            {% endfor %}
        </div>
    </div>
    
    <div class="card mb-4">
        <div class="card-header">
            代办列表
        </div>
        <div class="card-body">
            <div class="container" id="task_list">
                
            </div>
        </div>
    </div>
    
    <nav aria-label="Page navigation example" class="mb-4">
      <ul class="pagination justify-content-center">
        <li class="page-item {% if request.GET.prev|default:'0' == '-4' %}active{% endif %}"><a class="page-link" href="?prev=-4">前四天</a></li>
        <li class="page-item {% if request.GET.prev|default:'0' == '-3' %}active{% endif %}"><a class="page-link" href="?prev=-3">前三天</a></li>
        <li class="page-item {% if request.GET.prev|default:'0' == '-2' %}active{% endif %}"><a class="page-link" href="?prev=-2">前二天</a></li>
        <li class="page-item {% if request.GET.prev|default:'0' == '-1' %}active{% endif %}"><a class="page-link" href="?prev=-1">前一天</a></li>
        <li class="page-item {% if request.GET.prev|default:'0' == '0' %}active{% endif %}"><a class="page-link" href="?prev=0">今日</a></li>
        <li class="page-item"><a class="page-link" href="{% url 'core:week_manage' classid strdate %}">近一周</a></li> 
        <li class="page-item"><a class="page-link" href="#">近一月</a></li>
        <li class="page-item"><a class="page-link" href="#">本学期</a></li>
      </ul>
    </nav>
    
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-primary text-white h-100">
                <div class="card-body">
                    <h5 class="card-title">学生总数</h5>
                    <p class="card-text display-4">{{total_count}}</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-warning text-dark h-100">
                <div class="card-body">
                    <h5 class="card-title">迟到记录</h5>
                    <p class="card-text display-4">{{attendance_list.late_stats.morning|add:attendance_list.late_stats.afternoon|add:attendance_list.late_stats.evening}}</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-danger text-white h-100">
                <div class="card-body">
                    <h5 class="card-title">请假次数</h5>
                    <p class="card-text display-4">{{leave_discipline.leave_count}}</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-info text-white h-100">
                <div class="card-body">
                    <h5 class="card-title">违纪次数</h5>
                    <p class="card-text display-4">{{leave_discipline.discipline_count}}</p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5>班级考勤情况</h5>
                    <span id="task_number" class="badge bg-danger">您有1个任务未处理</span>
                </div>
                <div class="card-body">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>时间段</th>
                                <th>迟到次数</th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>上午</td>
                                <td>{{attendance_list.late_stats.morning}}次</td>
                                <td>{% if attendance_list.late_stats.morning > 3 %}<span class="text-danger">需关注</span>{% else %}<span class="text-success">正常</span>{% endif %}</td>
                            </tr>
                            <tr>
                                <td>下午</td>
                                <td>{{attendance_list.late_stats.afternoon}}次</td>
                                <td>{% if attendance_list.late_stats.afternoon > 3 %}<span class="text-danger">需关注</span>{% else %}<span class="text-success">正常</span>{% endif %}</td>
                            </tr>
                            <tr>
                                <td>晚上</td>
                                <td>{{attendance_list.late_stats.evening}}次</td>
                                <td>{% if attendance_list.late_stats.evening > 3 %}<span class="text-danger">需关注</span>{% else %}<span class="text-success">正常</span>{% endif %}</td>
                            </tr>
                        </tbody>
                    </table>
                    <div class="text-end mt-2">
                        <a href="{% url 'core:get_student_status' classid strdate %}" class="btn btn-sm btn-primary"><i class="bi bi-eye me-1"></i>查看详情</a>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card h-100">
                <div class="card-header">
                    <h5>作业提交情况</h5>
                </div>
                <div class="card-body">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>科目</th>
                                <th>未交数量</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for subject in subjects.subject_name_list %}
                            <tr>
                                <td>{{ subject }}</td>
                                <td>{{ subjects.no_homework_count|slice:forloop.counter0|last }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                    <div class="text-end mt-2">
                        <a href="{% url 'core:class_homework_stats' classid strdate %}" class="btn btn-sm btn-primary"><i class="bi bi-eye me-1"></i>查看详情</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 最近7天考勤统计图表 -->
    <div class="row mb-4">
        <div class="col-lg-12">
            <div class="card h-100 rounded-xl shadow-md overflow-hidden border-0">
                <div class="card-header bg-white border-bottom-0 py-4 px-5">
                    <h5 class="card-title text-gray-800 font-semibold">最近7天考勤统计</h5>
                </div>
                <div class="card-body p-5">
                    <canvas id="attendanceChart" height="300"></canvas>
                </div>
            </div>
        </div>
    </div>
    
    <div class="card mb-4">
        <div class="card-header">
            <h5>学生表现详情</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead >
                        <tr>
                            <th>学生姓名</th>
                            <th>迟到</th>
                            <th>作业没交</th>
                            <th>请假</th> 
                            <th>违纪</th>
                            <th>表彰</th>
                            <th>详细</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for student in performance_stats %}
                            <tr>
                                <td>{{ student.student_name }}</td>
                                <td>{% if student.late_count %}
                                    <span class="text-danger">{{student.late_count}}次</span>
                                    {% else %}
                                    <span class="text-success">无</span>
                                    {% endif %}
                                </td>
                                <td>{% if student.unsubmitted_homework %}
                                    <span class="text-danger">{{student.unsubmitted_homework}}次</span>
                                    {% else %}
                                    <span class="text-success">无</span>
                                    {% endif %}
                                </td>
                                <td>{% if student.leave_count %}
                                    <span class="text-danger">{{student.leave_count}}次</span>
                                    {% else %}
                                    <span class="text-success">无</span>
                                    {% endif %}
                                </td>
                                <td>{{student.discipline_count}}</td>
                                <td>{% if student.honor_count %}
                                    <span class="text-danger">{{student.honor_count}}次</span>
                                    {% else %}
                                    <span class="text-success">无</span>
                                    {% endif %}
                                </td>   
                                <td>
                                    <a href="{% url 'core:student_performance' student_id=student.student_id  strdate=data %}" class="btn btn-sm btn-success"><i class="bi bi-eye me-1"></i>查看</a>
                                </td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
</div>

<script>
    function fetchData() {
            $.ajax({
                url: '{% url 'core:get_tasks' classid %}',
                data: {
                    date: '{{strdate}}',
                    class_id: '{{classid}}',
                },
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                     $('#task_list').empty();
                    $.each(response.data,function(index,item){
                        $('#task_number').text(`您有${response.data.length}个任务未处理`);
                        
                        $('#task_list').append(`<div class="alert alert-info mt-2" role="alert"></div>`);
                        $('#task_list div:last-child').append(`
                            <a href="/core/tasks/${item.id}/" class="alert-link">${item.content}</a>
                        `);
                        
                    });
                    // 请求成功后，设置下一次请求
                    setTimeout(fetchData, 5000);
                },
                error: function(error) {
                    console.error('请求出错:', error);
                    
                    // 请求失败时，也设置下一次请求，可以考虑增加重试间隔
                    setTimeout(fetchData, 10000); // 失败时延长到10秒后重试
                }
            });
        }

        // 首次调用
        fetchData();
</script>

{% block extra_js %}
<script src="{% static 'bootstrap/jquery-3.6.0.min.js' %}"></script>
<script src="{% static 'bootstrap/bootstrap.bundle.min.js' %}"></script>
<script src="{% static 'chartjs/chart.umd.min.js' %}"></script>

<script>
    // 页面加载完成后初始化图表
    $(document).ready(function() {
        console.log('页面加载完成，开始初始化图表...');

        // 检查Chart.js是否加载成功
        if (typeof Chart === 'undefined') {
            console.error('Chart.js库未加载成功');
            $('.card-body:has(canvas)').html('<div class="text-center text-danger py-5"><i class="bi bi-exclamation-triangle fs-3 mb-2"></i><p>图表库加载失败，请检查网络连接后刷新页面</p></div>');
            return;
        }

        try {
            // 销毁已存在的图表实例
            if (window.attendanceChartInstance) {
                window.attendanceChartInstance.destroy();
                console.log('已销毁存在的图表实例');
            }

            // 直接嵌入JSON数据
            const attendanceLabels = {{ attendance_labels|safe }} || [];
            const presentData = {{ present_data|safe }} || [];
            const absentData = {{ absent_data|safe }} || [];

            // 检查数据是否为空
            if (attendanceLabels.length === 0 || presentData.length === 0 || absentData.length === 0) {
                console.warn('考勤数据为空，可能没有足够的考勤记录');
                if (attendanceLabels.length === 0) {
                    attendanceLabels.push('暂无数据');
                    presentData.push(0);
                    absentData.push(0);
                }
            }

            // 创建考勤图表
            const attendanceCtx = $('#attendanceChart')[0].getContext('2d');
            window.attendanceChartInstance = new Chart(attendanceCtx, {
                type: 'line',
                data: {
                    labels: attendanceLabels,
                    datasets: [
                        {
                            label: '出勤人数',
                            data: presentData,
                            backgroundColor: 'rgba(25, 135, 84, 0.1)',
                            borderColor: 'rgba(25, 135, 84, 1)',
                            borderWidth: 2,
                            tension: 0.3,
                            fill: true,
                            pointBackgroundColor: 'rgba(25, 135, 84, 1)',
                            pointRadius: 4,
                            pointHoverRadius: 6
                        },
                        {
                            label: '缺勤人数',
                            data: absentData,
                            backgroundColor: 'rgba(220, 53, 69, 0.1)',
                            borderColor: 'rgba(220, 53, 69, 1)',
                            borderWidth: 2,
                            tension: 0.3,
                            fill: true,
                            pointBackgroundColor: 'rgba(220, 53, 69, 1)',
                            pointRadius: 4,
                            pointHoverRadius: 6
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        intersect: false,
                        mode: 'index',
                    },
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                boxWidth: 12,
                                usePointStyle: true
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.7)',
                            padding: 12,
                            cornerRadius: 8
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            ticks: {
                                precision: 0
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    }
                }
            });
            console.log('图表初始化成功');
        } catch (error) {
            console.error('初始化图表时出错:', error);
            $('.card-body:has(canvas)').html('<div class="text-center text-danger py-5"><i class="bi bi-exclamation-triangle fs-3 mb-2"></i><p>图表初始化失败: ' + error.message + '</p></div>');
        }
    });
</script>

{% endblock %}
{% endblock %}